<template>
    <div class="channel-edit">
        <van-cell>
            <template #title>
                <span class="title-text">我的频道</span>
            </template>

            <template #value>
                    <van-button type="danger" round size="mini" plain class="edit-btn" @click="isEdit=!isEdit">{{ isEdit?"完成":"编辑" }}</van-button>
            </template>
           
        </van-cell>

        <van-grid :gutter="10" class="my-grid">
            <van-grid-item v-for="(channel, index) in myChannels" :key="channel.id"  class="grid-item">
                <template #default>
                        <van-icon 
                        name="clear"
                          v-show="isEdit && !fixChannels.includes(channel.id)"
                          ></van-icon>
                      <span class="channeltitle" :class="{ active: index === active }"  @click="myClicK(channel,index)">
                        <!-- a-{{ active }},i- {{ index }}  -->
                        {{ channel.name }} 
                    </span>
                </template>
              
            </van-grid-item>
        </van-grid>

        <van-cell>
            <template #title> <span class="title-text">频道推荐</span></template>
        </van-cell>

        <van-grid :gutter="10" class="recommend-grid">
            <van-grid-item v-for="channel in recomm" :key="channel.id" icon="plus" :text="channel.name" class="grid-item"
            @click="addOneChannel(channel)"
             />
             <!-- <van-grid-item v-for="channel in state.allChannels" :key="channel.id" icon="plus" :text="channel.name" class="grid-item"
            @click="addOneChannel(channel)"
             /> -->
        </van-grid>
    </div>
</template>

<script>
import { ref, onMounted, reactive,computed, nextTick,watch, toRefs  } from 'vue';
import { getAllChannels,addUserChannel,deleteUserChannel } from "../../../api/channel";
import { useStore }  from "vuex";
import { setItem } from "../../../utils/storage"


//移除频道
function useMyClick(state,emit,{myChannels,active},store){

    const myClicK=async (channel,index)=>{
        console.log("移除我的频道",channel,index,"激活编号",active);
        if(state.isEdit)
        {
            //如果是推荐频道,禁止删除
            if(state.fixChannels.includes(channel.id))return             
            //编辑状态,执行删除操作
            if(index<=active)
            {
                active=active-1;
                emit('update-active',active,true);
            }
            //编辑状态,执行删除
            myChannels.splice(index,1);
            //判断用户是否登录
            if(store.state.user)
            {
                //用户已经登录
             await   deleteUserChannel(channel.id,store.state.user.data.id)


            }else
            {
                //未登录
                setItem("TOUTIAO_CHANNELS",myChannels);

            }




        }else
        {
            //非编辑状态,执行的频道的切换
            emit('update-active',index,false);
        }

    }
    return {myClicK}
}


function useChannels(state,props) {
    

    const loadAllChannels = async () => {
        const { data } = await getAllChannels();        
        state.allChannels = data.data.channels;
       // console.log("load allchannels result",state.allChannels);

    } 
 
//   nextTick(() => {  
//     console.log("next tick",state.allChannels); // 确保此时DOM已经更新，并检查值是否正确  
//     });
/**
 * // 定义两个对象数组  
const a = [{id: 1, name: 'test1'}, {id: 2, name: 'test2'}, {id: 3, name: 'test3'}];  
const b = [{id: 2, name: 'test2'}, {id: 4, name: 'test4'}];  
  
// 使用forEach循环检查数组a中的每个对象是否存在于数组b中  
a.forEach(item => {  
    const found = b.find(itemB => itemB.id === item.id);  
    if (found) {  
        console.log(`在数组b中找到id为 ${item.id} 的元素`);  
    } else {  
        console.log(`在数组b中未找到id为 ${item.id} 的元素`);  
    }  
});
 */

     const recomm = computed(() => { 
        //console.log("90",state.allChannels,"prop channels",props.myChannels);
       //  return state.allChannels.filter(element => !props.myChannels.includes(element.id));

         let  arrayA  = [];
         state.allChannels.forEach(item => {  
            const found = props.myChannels.find(itemB => itemB.id === item.id);  
            if (!found) {  
                arrayA.push(item);
            // console.log(`在数组b中未找到id为 ${item.id} 的元素`);  
            }  
        })  
        return arrayA;
     });
    

    onMounted(() => {
        loadAllChannels();

   /*      setTimeout(() => {  
            console.log("3s 后频道列表",state.allChannels);
      }, 3000);   */
    });

    return {       
      recomm
    }
}

//添加频道
function useAddOneChannel(props,store){
   // const store=useStore();
    const addOneChannel= async (channel)=>{
        props.myChannels.push(channel); 
        //数据持久化的处理
        if(store.state.user)
        {
            console.log(store.state);
            const channelContent={
                userid:store.state.user.data.id,
                channel
            }
            //已经登录,把数据存储到服务端
           await addUserChannel(channelContent);
        }
        else
        {
            //未登录,把数据存储到本地
            setItem("TOUTIAO_CHANNELS",props.myChannels);
        }
    }

    return {addOneChannel}
}


export default {
    //组件使用项目  
    props: {
        myChannels: {
            type: Array, 
            required: true,
        },
        active: {
            type: Number, 
            required: true,
        }
    },
    //使用组件 

    emits:['update-active'],
    setup(props,{emit}) {
        const state=reactive({
            allChannels: [], 

            isEdit:false,
            fixChannels:[1] //不允许删除的频道的编号存储
        });
        const store=useStore();

        return {
            ...useChannels(state,props),
            ...useAddOneChannel(props,store),
            ...toRefs(state),
            ...useMyClick(state,emit,props,store )
        }
       // useChannels(props);
    },
};
</script>
<style>
.channel-edit {
    padding: 85px 20px;
}

.channel-edit .title-text {
    font-size: 20px;
    color: #363636;
}

.channel-edit .edit-btn {
    width: 80px;
    height: 36px;
    font-size: 16px;
}

.channel-edit .grid-item {
    width: 86px;
    height: 66px;
    background-color: #f6f5f6;
    overflow: hidden;
}

.channel-edit .van-grid-item__text {
    font-size: 14px;
    color: #393939;
    margin-top: 0;
}

.channel-edit .recommend-grid .van-grid-item__content {

    flex-direction: row;
    white-space: nowrap;
}

.channel-edit .recommend-grid .van-icon {
    font-size: 16px;
    margin-right: 4px;
}

.channel-edit .my-grid .grid-item .van-icon-clear {
    position: absolute;
    right: 0px;
    top: 0px;
    font-size: 17px;
    color: #cacaca;
    z-index: 2;

}

.channel-edit .channeltitle {
    font-size: 14px;
    color: #393939;
    margin-top: 0px;
}

.channel-edit .grid-item .active {
    color: red;
}</style>